import cloud from '@lafjs/cloud'
let data
const db = cloud.mongo.db
let dbName = 'class-album'

export default async function (ctx: FunctionContext) {
  data = ctx.body.data
  switch (ctx.body.type) {
    case "query":
      return await query()
      break;
    case "save":
      return await save()
      break;
    default:
      break;
  }
}

async function query() {
  let aa = await db.collection(dbName).find(data).sort({ _add_time: 1 }).toArray()
  return cloud.utils.requestReturn({ data: aa })
}

async function save() {
  let classId = data[0].classId
  await cloud.utils.deleteData(dbName, { classId })
  for (let index = 0; index < data.length; index++) {
    const element = data[index];
    await cloud.utils.addData(dbName, element)
  }
  return cloud.utils.requestReturn({ data: "" })
}
